<?php

/**
 * This file is part of the Pagizer package.
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 *
 * @copyright   Copyright (c) 2010 Advisa (http://www.advisa.fr)
 * @author      Pagizer Core Team <team@pagizer.org>
 * @package     pagizer
 * @subpackage  medias
 */

class m_medias_documents_Media extends m_medias_documents_MediaBase
{
	/* @var $fileObject f_file_File */
	private $fileObject;
    private $linkObject;
	const IMAGES_ROOT = "images";
	private $linkedMedia="";
	/**
	 * @return m_medias_documents_Media
	 */
	public static function createNew()
	{
		return new self();
	}
	
	/**
	 * @return m_medias_documents_Media
	 */
	public static function getInstanceByUniqueId($id, $lang = null)
	{
		if(is_null($lang)) $lang = f_core_Context::getInstance()->getLang();
		$cache = f_core_Cache::getInstance();
		
		$key = $cache->getDocumentCacheKey($id, $lang);
		
		if($cache->hasCache($key))
		{
			return $cache->getCacheContent($key);
		}
		
		$object = new self($id, $lang);
		
		$cache->putInCache($key, $object);
		
		return $object;
	}
	
	/**
	 * Delete all images before deleting in db
	 */
	protected function preDelete()
	{
		$folders = array("icons", "preview", "mceIcons");
		$fileName = $this->getUniqueId().".".$this->getExtension();

		foreach($folders as $folder)
		{
			$filePath = HTTP_DIR.DS.self::IMAGES_ROOT.DS.$folder.DS.$fileName;
					
			if(is_file($filePath))
			{
				@unlink($filePath);
			}
		}
		
		$files = $this->getAllMediaPathList();

		if(is_array($files) && count($files) > 0)
		{
			foreach($files as $file)
			{
				if(is_file($file))
				{
					@unlink($file);
				}
			}
		}
	}
	
// *********************************************************************** BACKOFFICE METHODS	
	
	/**
	 * Create linked file used in backoffice
	 *
	 * @param string $folder
	 * @param integer $maxWidth
	 * @param integer $maxHeight
	 */
	private function createBackOfficeFile($folder, $maxWidth, $maxHeight)
	{
		list($mainType, $type) = explode("/", $this->getMime());

		if(strtolower($mainType) == "image")
		{
			$origFile = $this->getFilePath($this->getLabel());
			$sizes = f_utils_Picture::getProportionalSizeByMaxSize($origFile, $maxWidth, $maxHeight);
			$file = $this->getFileObject();
			$filePath = HTTP_DIR.DS.self::IMAGES_ROOT.DS.$folder.DS;
			$fileName = $this->getUniqueId().".".$file->getExtension();
			$destFile = $filePath.$fileName;
			
			if(!is_dir($filePath))
			{
				mkdir($filePath, 0777, true);
			}
			
			f_utils_Picture::createThumb($origFile, $destFile, $maxWidth, $maxHeight);			
		}
	}
	
	/**
	 * Get linked backoffice images like icon or preview
	 *
	 * @param string $folder
	 * @return string
	 */
	private function getBackOfficeFile($folder)
	{
		$fileObj = $this->getFileObject();
		$filePath = HTTP_DIR.DIRECTORY_SEPARATOR.self::IMAGES_ROOT.DIRECTORY_SEPARATOR.$folder.DIRECTORY_SEPARATOR;
		$fileName = $this->getUniqueId().".".$fileObj->getExtension();
		$file = $filePath.$fileName;
		
		if(is_file($file))
		{
			return URL_RELATIVE."/images/".$folder."/".$fileName;
		}
		return null;
	}
	
	/**
	 * Create document icon if file is an image
	 */
	public function createIcon()
	{
		$this->createBackOfficeFile("icons", 16, 16);
	}
	
	/**
	 * Get backoffice linked icon for current document
	 *
	 * @return string
	 */
	public function getIcon($cache = false, $getMime = false, $size = '1616')
	{
        $file = $getMime == false ? $this->getBackOfficeFile("icons") : null;

		if(!is_null($file))
        {
            return ($cache == true) ? $file."?".rand(0,50) : $file;
        }
		
		$mimeType = str_replace("/", "_", $this->getMimeType());

        if(is_file(HTTP_DIR.DS.'themes'.DS.BACK_THEME.DS.'backend'.DS.'medias'.DS.'icons'.DS.$size.DS.'mimetypes'.DS.'mime_'.$mimeType.'.png'))
        {
            return URL_RELATIVE.'/themes/'.BACK_THEME.'/backend/medias/icons/'.$size.'/mimetypes/mime_'.$mimeType.'.png';
        }

        list($mainType, $precise) = explode('_', $mimeType);

        if(is_file(HTTP_DIR.DS.'themes'.DS.BACK_THEME.DS.'backend'.DS.'medias'.DS.'icons'.DS.$size.DS.'mimetypes'.DS.'mime_'.$mainType.'.png'))
        {
            return URL_RELATIVE.'/themes/'.BACK_THEME.'/backend/medias/icons/'.$size.'/mimetypes/mime_'.$mainType.'.png';
        }

		return URL_RELATIVE.'/themes/'.BACK_THEME.'/backend/medias/icons/'.$size.'/mimetypes/mime_default.png';
	}
	
	/**
	 * Create preview if file is an image
	 */
	public function createPreview()
	{
		$this->createBackOfficeFile("preview", 400, 400);
	}
	
	/**
	 * Get preview if file is an image
	 *
	 * @return string
	 */
	public function getPreview($cache = false)
	{
		$file = $this->getBackOfficeFile("preview");

        if(!is_null($file))
        {
            if($cache == true)
                return $file."?".rand(0,50);
            else
                return $file;
        }
	}

    public function getLinkPreview($picture = false)
    {
        if($this->isLink())
        {
            if($picture)
            {
                return $this->getLinkObject()->getImageURL();
            }
            else
            {
                $this->getLinkObject()->setWidth('300');
                $this->getLinkObject()->setHeight('200');
                return $this->getLinkObject()->getEmbedCode();
            }
        }

        return false;
    }
	
	/**
	 * Create mce icon if file is an image
	 */
	public function createMceIcon()
	{
		$this->createBackOfficeFile("mceIcons", 96, 96);
	}
	
	/**
	 * Get mce icon if file is an image
	 *
	 * @return string
	 */
	public function getMceIcon()
	{
		return $this->getBackOfficeFile("mceIcons");
	}
	
// *********************************************************************** FILE MANIPULATION METHODS	
	
	/**
	 * Get parent folders for current document
	 *
	 * @return array
	 */
	private function getParents($withLang = true)
	{
		$parents = f_relation_ManagerNew::getInstance($this)
                                    ->getParents()
                                    ->withModel("backoffice/folder")
                                    ->withLang($this->getLang())
                                    ->recursively()
                                    ->retrieveIdsAndModels();

		if(!is_array($parents))
		{
			return array();
		}
		else
		{
            $parents = array_reverse($parents);
			foreach($parents as $parent)
			{
				$ids[] = $parent['id'];
			}
		}
	
		if($withLang)
		{
			array_push($ids, strtolower($this->getLang()));
		}
	
		return $ids;
	}
	
	public function getFolder()
	{
		return f_relation_ManagerNew::getInstance($this)->getParents()->withRelationType("media")->withLang($this->getLang())->retrieveDocuments();
	}
	
	public function getFolderId()
	{
		$folder = $this->getFolder();
		
		if(is_object($folder) && $folder instanceof m_backoffice_documents_Folder)
		{
			return $folder->getUniqueId();
		}
		
		return null;
	}
	
	/**
	 * Get file object
	 *
	 * @return f_file_File
	 */
	private function getFileObject()
	{
		if(is_null($this->fileObject) || $this->fileObject->getBaseName() != $this->getLabel())
		{
			$this->fileObject = f_file_File::getInstance($this->getFilePath($this->getLabel()));
		}

		return $this->fileObject;
	}

    private function getLinkObject()
    {
        if(is_null($this->linkObject))
        {
            $this->linkObject = f_utils_AutoEmbed::getInstance();
            $this->linkObject->parseUrl($this->getLabel());
        }

        return $this->linkObject;
    }
	
	/**
	 * Return root path to the physical files
	 *
	 * @example /home/web/myproject/images/34/36/fr
	 * @param string $lang
	 * @return string
	 */
	public function getRootFilePath($lang = null)
	{		
		if(is_null($lang))
		{
			return HTTP_DIR.DS.self::IMAGES_ROOT.DS.join(DIRECTORY_SEPARATOR, $this->getParents(false));
		}
		else
		{
			return HTTP_DIR.DS.self::IMAGES_ROOT.DS.join(DIRECTORY_SEPARATOR, $this->getParents(false)).DS.strtolower($lang);
		}
	}
	
	/**
	 * Get real path to related file
	 *
	 * @param string $filename
	 * @return string
	 */
	public function getFilePath($filename = null)
	{        
		return HTTP_DIR.DS.self::IMAGES_ROOT.DS.join(DS, $this->getParents()).DS.$filename;
	}
	
	/**
	 * Get url to related file
	 *
	 * @param string $filename
	 * @return string
	 */
	public function getFileUrl($filename = null)
	{	
		if(is_null($filename))
		{
			$filename = $this->getFileNameWoExt().".".$this->getExtension();
		}

		return URL_RELATIVE.'/'.self::IMAGES_ROOT.'/'.join('/', $this->getParents()).'/'.$filename;
	}
	
	/**
	 * Return linked filename without extension
	 *
	 * @return string
	 */
	public function getFileNameWoExt()
	{
		return $this->getFileObject()->getFileName();		
	}
	
	/**
	 * Get linked file extension
	 *
	 * @return string (ex: jpg, gif)
	 */
	public function getExtension()
	{
		if(is_null($this->getExt()))
		{
			return $this->getFileObject()->getExtension();			
		}
		return $this->getExt();
	}
	
	/**
	 * Enter description here...
	 *
	 * @return unknown
	 */
	public function getDimensions()
	{
		if($this->isImage())
		{
			return $this->getFileObject()->getDimensions();
		}

        if($this->isLink())
        {
            return array($this->getLinkObject()->getWidth(), $this->getLinkObject()->getHeight());
        }

		return null;
	}
	
	public function getWidth()
	{
		if($this->isImage() || $this->isLink())
		{
			$dim = $this->getDimensions();
			return $dim[0];
		}
		return null;
	}
	
	public function getHeight()
	{
		if($this->isImage() || $this->isLink())
		{
			$dim = $this->getDimensions();
			return $dim[1];
		}
		return null;
	}
	
	/**
	 * Check if associated file is an image
	 *
	 * @return boolean
	 */
	public function isImage()
	{	
		return $this->getFileObject()->isImage();
	}

    public function isLink()
    {
		if($this->getMimeType() != "")
		{
			list($mainType, $mimeType) = explode("/", $this->getMimeType());
			return (strtolower($mainType) == "link");
		}
		return false;
    }
	
	/**
	 * Get file raw mime type (ex : image/png)
	 *
	 * @return string
	 */
	public function getMimeType()
	{
		if(is_null($this->getMime()))
		{
			$this->getFileObject();
			$file = $this->fileObject;		
			return $file->getMimeType();
		}
		else
		{
			return $this->getMime();
		}
	}
	
	public function getMimeTypeIconName()
	{
		return "mime_".str_replace("/", "_", $this->getMimeType()).".png";
	}
	
	/**
	 * Get formatted mime type (ex : Image PNG)
	 *
	 * @return string
	 */
	public function getFormattedMimeType()
	{
		if($this->isImage())
		{
            $string = f_locale_Manager::getLocale("medias.locales.image");
			$string = $string . " " . strtoupper($this->fileObject->getExtension());
		}
		elseif($this->isLink())
        {
            $string = $this->getExtension();
        }
        else
		{
            $string = f_locale_Manager::getLocale("medias.locales.file");
			$string = $string . " " . strtoupper($this->fileObject->getExtension());
		}

        return $string;
	}	
	
	/**
	 * Get formatted file size (ex : 12ko, 12Mo)
	 *
	 * @return unknown
	 */
	public function getSize()
	{
        if(!$this->isLink())
        {
            $this->getFileObject();
            $file = $this->fileObject;
            return $file->getFilesizeFormatted($this->getContext()->getDisplayLang());
        }

        return null;
	}
	
	public function getEditUrl($folderId = null, $lang = null, $tabName = null)
	{
        if(is_null($folderId))
        {
            $folderId = $this->getDocumentParent()->getUniqueId();
        }

		if(is_null($lang))
		{
			$lang = f_core_Request::getInstance()->getParameter("docLang", $this->getLang());
		}
		
		if(is_null($tabName))
		{
			$tabName = "properties";
		}
		
		return f_core_Routing::getUrl("mediasEdit", array("tabName" => $tabName, "docId" => $folderId, "mediaId" => $this->getUniqueId(), "docLang" => strtolower($lang)));
	}

    public function downloadFile()
    {
        $this->getFileObject()->forceDownload($this->getLabel());
    }
	
	public function canSlide()
	{
		return false;
	}
	
// *********************************************************************** IMAGE MANIPULATION METHODS		
	
	public function countResizedImages()
	{
		if($this->isImage())
		{
			return count($this->getAllSizesImagesPathList());
		}
		return null;
	}
	
	
	public function getImageUrlFromPath($path)
	{
		return str_replace(HTTP_DIR, URL_RELATIVET, $path);
	}
	
	public function getImageObjectFromPath($path)
	{
		return f_file_File::getInstance($path);
	}
	
	public function getAllSizesImagesObjects($orderMethod = null, $reverseOrder = false)
	{
		if(is_null($orderMethod))
		{
			$orderMethod = "getFileName";
		}
		
		if($this->isImage())
		{
			$files = $this->getAllSizesImagesPathList();

			if(is_array($files))
			{
                $obj = array();
                
				foreach($files as $file)
				{
					$image = $this->getImageObjectFromPath($file);
					$obj[$image->$orderMethod()] = $image;
				}

				$reverseOrder ? rsort($obj) : sort($obj);
				
				return $obj;
			}
		}
		return null;			
	}
	
	public function getAllSizesImagesPathList()
	{
		if($this->isImage())
		{
            $original = f_file_Resolver::getInstance()->fromDirectory($this->getRootFilePath($this->getLang()))->setMask($this->getFileNameWoExt().".".$this->getExtension())->find();
			$sized = f_file_Resolver::getInstance()->fromDirectory($this->getRootFilePath($this->getLang()))->setMask($this->getFileNameWoExt()."_*.".$this->getExtension())->find();

            return array_merge($original, $sized);
		}
		return null;
	}

	public function getAllSizesImagesUrlList($woOriginal = false, $rsort = false)
	{
		if($this->isImage())
		{
			$files = $this->getAllSizesImagesPathList();
			
			if(is_array($files))
			{
				foreach($files as $file)
				{
					$urls[] = $this->getImageUrlFromPath($file);
				}
				
				if($woOriginal) { unset($urls[0]); }
				if($rsort) { rsort($urls); }
				
				return $urls;
			}
		}
		
		return null;
	}
	
	public function getImageUrlByMaxSize($maxWidth, $maxHeight, $keepRatio = false)
	{
		if($this->isImage())
		{
			$origFile = $this->getFilePath($this->getLabel());

			if($keepRatio == true)
			{
			    $sizes = f_utils_Picture::getProportionalSizeByMaxSize($origFile, $maxWidth, $maxHeight);
			}
			else
			{
			    $sizes["width"] = $maxWidth;
			    $sizes["height"] = $maxHeight;
			}

			$file = $this->getFileObject();	

			$fileName = $this->getFileNameWoExt()."_".$sizes['width']."_".$sizes['height'].".".$file->getExtension();

			$resizedFile = $this->getFilePath($fileName);

			if(is_file($resizedFile))
			{
				return $this->getFileUrl($fileName);
			}
			else
			{
			    $files = $this->getAllSizesImagesUrlList(true);
			    if(count($files) > 0)
			    {
                    $all = array();

                    foreach($files as $file)
                    {
                        $list = explode("/", $file);
                        $fileName = end($list);
                        $prefix = explode(".", $fileName);
                        $elements = explode("_", $prefix[0]);
                        $picWidth = $elements[count($elements)-2];
                        $picHeight = $elements[count($elements)-1];

                        if($picWidth <= $maxWidth && $picHeight <= $maxHeight)
                        {
                            $diffWidth = intval($maxWidth) - intval($picWidth);
                            $diffHeight = intval($maxHeight) - intval($picHeight);
                            $diff = $diffWidth + $diffHeight;
                            $all[$diff] = $file;
                        }
                    }

                    if(count($all) > 0)
                    {
                        return $all[min(array_keys($all))];
                    }
			    }
			}

            $origDimensions = $this->getDimensions();

            if($origDimensions[0] <= $sizes['width'] && $origDimensions[1] <= $sizes['height'])
            {
                return $this->getFileUrl($this->getFileNameWoExt().'.'.$this->getExtension());
            }
		}

		return null;
	}

    public function isMediaSize($width, $height)
    {
        $fileName = $this->getFileNameWoExt()."_".$width."_".$height.".".$this->getExt();
        $resizedFile = $this->getFilePath($fileName);
        if(is_file($resizedFile))
        {
            return true;
        }

        return false;
    }
	
	public function moveMedia($destFolder)
	{
		$lang = strtolower($this->getLang());
		$fileName = $this->getFileNameWoExt().".".$this->getExtension();
		
        $parents = f_relation_ManagerNew::getInstance($destFolder)->getParents()->withModel($destFolder->getDocumentModel())->withLang($lang)->retrieveIdsAndModels();
        $ids = array();
        if(!is_null($parents))
        {
            foreach($parents as $parent)
            {
                $ids[] = $parent['id'];
            }
        }

        $saveRootPath = HTTP_DIR.DS.self::IMAGES_ROOT.DS.join(DS, $ids).DS.$destFolder->getUniqueId();
        $savePath = $saveRootPath.DS.$lang;
		
		if(!is_dir($savePath))
		{
			mkdir($savePath, 0777, true);
		}

        if($this->isImage())
        {
            $allPath = $this->getAllSizesImagesObjects();
            if(count($allPath) > 0)
            {
                foreach($allPath as $path)
                {
                    $saveFilePath = $savePath.DS.$path->getFileName().".".$path->getExtension();

                    if(file_exists($saveFilePath))
                    {
                        return f_locale_Manager::getLocale("medias.locales.fileExist", null, array('file' => $path->getFileName()));
                    }

                    copy($path->getFile(), $saveFilePath);
                    unlink($path->getFile());
                }
            }
        }
        else
        {
            $saveFilePath = $savePath.DS.$this->getFileNameWoExt().".".$this->getExtension();

            if(file_exists($saveFilePath))
            {
                return f_locale_Manager::getLocale("medias.locales.fileExist", null, array('file' => $this->getFileNameWoExt().".".$this->getExtension()));
            }

            copy($this->getFilePath($this->getFileNameWoExt().".".$this->getExtension()), $saveFilePath);
            unlink($this->getFilePath($this->getFileNameWoExt().".".$this->getExtension()));
        }
		
		return true;
	}

    public function renameMedia($newName)
    {
        $mainMedia = $this->getFileObject();

        if(file_exists($this->getFilePath($newName).".".$this->getExtension()))
        {
            return false;
        }
        
        if($mainMedia->isImage())
        {
            $allImages = $this->getAllSizesImagesObjects();
            unset($allImages[0]);

            if(!empty($allImages))
            {
                foreach($allImages as $image)
                {
                    $end = substr($image->getBaseName(), strlen($mainMedia->getFileName()));
                    rename($image->getFile(),$image->getDir().DS.$newName.$end);
                }
            }
        }

        return rename($mainMedia->getFile(),$mainMedia->getDir().DS.$newName.".".$mainMedia->getExtension());
    }
	
	public function resizePicture($maxWidth, $maxHeight)
	{		
		if($this->isImage())
		{
			$origFile = $this->getFilePath($this->getLabel());
			$sizes = f_utils_Picture::getProportionalSizeByMaxSize($origFile, $maxWidth, $maxHeight);
			$file = $this->getFileObject();
			
			if(!is_dir($this->getFilePath()))
			{
				mkdir($this->getFilePath(), 0777, true);
			}
			
			$destFile = $this->getFilePath($this->getFileNameWoExt()."_".$sizes['width']."_".$sizes['height'].".".$file->getExtension());
			f_utils_Picture::createThumb($origFile, $destFile, $maxWidth, $maxHeight);			
		}
	}

	public function advancedResizePicture($destWidth, $destHeight, $mode = 1, $cropWidth = 0, $cropHeight = 0, $offsetX = 0, $offsetY = 0, $bgColor = "000000", $force = "0", $quality = 80)
	{
		if($this->isImage())
		{
            $imgSrc = $this->getFilePath($this->getFileNameWoExt().".".$this->getExtension());

            if(!file_exists($imgSrc))
            {
                return "404";
            }

            if($bgColor != 'transparent')
            {
                list($r, $v, $b) = m_medias_services_MediaService::getInstance()->getBgColor($bgColor);
            }
            
            list($srcWidth, $srcHeight, $type) = GetImageSize($imgSrc);

            switch ($type)
            {
                case 1:
                    $pic = imagecreatefromgif($imgSrc);
                break;
                case 2:
                    $pic = imagecreatefromjpeg($imgSrc);
                break;
                case 3:
                    $quality = ($quality - 100) / 11.111111;
                    $quality = round(abs($quality));
                    $pic = imagecreatefrompng($imgSrc);
                break;
                default:
                    return false;
                break;
            }

            $values = $this->getModeSize($srcWidth, $srcHeight, $destWidth, $destHeight, $mode);
            extract($values,EXTR_OVERWRITE);

            if($pic !== false)
            {
                $newPic = function_exists('ImageCreateTrueColor') == true ? ImageCreateTrueColor($destWidth,$destHeight) : ImageCreate($destWidth,$destHeight);
                if (function_exists('ImageCopyResampled'))
                {
                    ImageCopyResampled($newPic, $pic, 0, 0, 0, 0, $destWidth, $destHeight, $srcWidth, $srcHeight);
                }
                else
                {
                    ImageCopyResized($newPic, $pic, 0, 0, 0, 0, $destWidth, $destHeight, $srcWidth, $srcHeight);
                }

                // png transparency
                if($type == 3 && $bgColor == 'transparent')
                {
                    imagealphablending($newPic, false);
                    imagesavealpha($newPic,true);
                    $transparent = imagecolorallocatealpha($newPic, 255, 255, 255, 127);
                    imagefill($newPic, 0, 0, $transparent);
                }
                
                if($mode == 0)
                {
                    $cropPic = imagecreatetruecolor($cropWidth, $cropHeight);

                    if($bgColor != 'transparent')
                    {
                        $color = imagecolorallocate($cropPic, hexdec('0x' . $r), hexdec('0x' . $v), hexdec('0x' . $b));
                    }
                    else
                    {
                        if($type == 3)
                        {
                            imagealphablending($cropPic, false);
                            imagesavealpha($cropPic,true);
                            $transparent = imagecolorallocatealpha($cropPic, 255, 255, 255, 127);
                            imagefill($cropPic, 0, 0, $transparent);
                        }
                        else
                        {
                            $color = imagecolorallocate($cropPic, hexdec('0xFF'), hexdec('0xFF'), hexdec('0xFF'));
                        }
                    }
                    

                    imagecopyresampled(	$cropPic,
                                        $newPic,
                                        $offsetX,
                                        $offsetY,
                                        0,
                                        0,
                                        $destWidth,
                                        $destHeight,
                                        $destWidth,
                                        $destHeight);

                    $newPic = $cropPic;
                    $destWidth = $cropWidth;
                    $destHeight = $cropHeight;
                }

                $imgDest = $this->getFilePath($this->getFileNameWoExt()."_".$destWidth."_".$destHeight.".".$this->getExtension());

                if(file_exists($imgDest) && $force == "0")
                {
                    return "50";
                }

                switch($type)
                {
                    case 1:
                        imagegif($newPic, $imgDest, $quality);
                    break;
                    case 2:
                        imagejpeg($newPic, $imgDest, $quality);
                    break;
                    case 3:
                        imagepng($newPic, $imgDest, $quality);
                    break;
                }

                @imagedestroy($pic);
                @imagedestroy($newPic);
            }

            if(file_exists($imgDest))
            {
                return true;
            }
        }

        return false;
	}

    private function getModeSize($srcWidth, $srcHeight, $destWidth, $destHeight, $mode)
    {
        $result = array();

        $ratioHeight = round(($destWidth / $srcWidth) * $srcHeight);
        $ratioWidth = round(($destHeight / $srcHeight) * $srcWidth);

        switch($mode)
        {
            case 2:
                $result['destWidth'] = $ratioWidth;
            break;
            case 3:
                $result['destHeight'] = $ratioHeight;
            break;
            case 4:
                if($ratioHeight < $destHeight)
                {
                    $result['destWidth'] = $ratioWidth;
                    $result['offsetX'] = round(($destWidth - $ratioWidth) / 2);
                }
                else
                {
                    $result['destHeight'] = $ratioHeight;
                    $result['offsetY'] = round(($destHeight - $ratioHeight) / 2);
                }

                $result['cropWidth'] = $destWidth;
                $result['cropHeight'] = $destHeight;
                $result['mode'] = 0;
            break;
            default:
                if($ratioHeight > $destHeight)
                {
                    $result['destWidth'] = $ratioWidth;
                }
                else
                {
                    $result['destHeight'] = $ratioHeight;
                }
            break;
        }

        return $result;
    }

	public function getAllMediaPathList()
	{
        return f_file_Resolver::getInstance()->fromDirectory($this->getRootFilePath($this->getLang()))->setMask($this->getFileNameWoExt()."*.".$this->getExtension())->find();
	}

    public function setLinkedMedia($med)
    {
        $this->linkedMedia=$med;
    }

    public function getLinkedMedia()
    {
        return $this->linkedMedia;
    }

    public function getBoSearchIcon()
    {
        return $this->getIcon();
    }
}